package org.wadael.waverobotfrmwrk.utils;

import java.util.ArrayList;
import java.util.List;

import org.wadael.waverobotfrmwrk.advanced.Command;
import org.wadael.waverobotfrmwrk.advanced.WithDelimitedCommandsRobot;


/**
 * Placeholder for command-oriented code. 
 * 
 * @author jerome baton : Wadael, http://blog.wadael.org
 *
 */
public class CommandUtils {

	/**
	 * Returns a list of command in presence order (beginning to end).
	 * 
	 * TODO test order with right-to-left languages
	 * 
	 * @param blipText the text of a blip, to parse so to isolate commands.
	 * @return
	 */
	public static List<Command> parseCommands(String blipText,  WithDelimitedCommandsRobot parentRobot){
		if(blipText==null || parentRobot ==null) return null;
		ArrayList<Command> listCommands = new ArrayList<Command>();
		
		String commandBeginning = parentRobot.getStartCommandDelimiter() + parentRobot.getRobotIdentifier() + parentRobot.getAcronymAndCommandSeparator();
		int commandBeginningLength = commandBeginning.length();
		
		int posFoundBeginning = -1;
		int lastPosFoundBeginning = 0;
		int spacePos = 0;
		int endPos = 0;
		
		// {my:CAP A-F}
		
		while( (posFoundBeginning = blipText.indexOf(commandBeginning, lastPosFoundBeginning)) != -1){
			Command c = new Command();
			c.setAcronym(parentRobot.getRobotIdentifier());
			
			spacePos = blipText.indexOf(" ", posFoundBeginning );
			endPos = blipText.indexOf( parentRobot.getEndCommandDelimiter(), posFoundBeginning+1 );
			
			if(spacePos != -1 && spacePos < endPos ){
				// so there must be parameters
				int a = posFoundBeginning+commandBeginningLength ;
				c.setInstruction( blipText.substring(a, spacePos) );
				
				int b = spacePos+1 ;
				c.setParameters( blipText.substring(b, endPos) );
				listCommands.add(c);
			}
			else{
				if(endPos != -1){
					c.setInstruction( blipText.substring(posFoundBeginning+commandBeginningLength, endPos) );
					c.setParameters( null) ;
					listCommands.add(c);
				}
			}
			
			lastPosFoundBeginning = posFoundBeginning+1; 
		}
		return listCommands;
	}
}
